package com.wxg.tools.cmd;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.SequenceInputStream;
import java.util.ArrayList;
import java.util.List;

import org.junit.Test;

/**
 * version 1.0
 * @author wxg
 *
 */
public class JavaRuntimeExec {

	@Test
	public void test001(){
		String aa = System.getenv("JAVA_HOME1");
		if(null != aa){
			System.out.printf("aa : %s", aa);
		}
		System.out.printf("no evn");
	}
	
	
	private final String version = "1.0";

	private Process process = null;
	
	private Runtime currentRuntime = null;
	
	private String javaHome = null;
	
	private BufferedReader reader = null;
	
	private BufferedWriter writer = null;
	
	public JavaRuntimeExec(){
		currentRuntime = Runtime.getRuntime();
		javaHome = System.getenv("JAVA_HOME");
	}
	
	public String getVersion() {
		return version;
	}
	
	public Process getProcess() {
		return process;
	}
	
	public void setJavaHome(String javaHome) {
		this.javaHome = javaHome;
	}
	
	public Process runtimeExec(List<String> commands, String dir){
		String[] emptyarr = new String[]{};
		return runtimeExec(commands.toArray(emptyarr), dir);
	}
	
	public Process runtimeExec(String[] commands, String dir){
		String[] emptyarr = new String[]{};
		List<String> env = new ArrayList<String>();
		env.add("JAVA_HOME=" + javaHome);
		env.add("PATH=" + System.getenv("Path"));
		
		return runtimeExecPrivate(commands, env.toArray(emptyarr), new File(dir));
	}
	
	public Process runtimeExec(List<String> commands, List<String> env, File dir){
		String[] emptyarr = new String[]{};
		return runtimeExecPrivate(commands.toArray(emptyarr), env.toArray(emptyarr), dir);
	}
	
	public Process runtimeExec(String[] commands, String[] env, File dir){
		return runtimeExecPrivate(commands, env, dir);
	}
	
	private Process runtimeExecPrivate(String[] commands, String[] env, File dir){
		try {
			process = currentRuntime.exec(commands, env, dir);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return process;
	}
	
	public void destroy(){
		try {
			if(null != reader){
				reader.close();
			}
			if(null != writer){
				writer.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		if(process.isAlive()){
			process.destroy();
		}
	}
	
	public BufferedReader fetchReader(){
		InputStream in = process.getInputStream();
		InputStream errin = process.getErrorStream();
		/**
		 * SequenceInputStream
		 * 这里这样用， 是否正确呢？ 
		 */
		SequenceInputStream sis = new SequenceInputStream(in, errin);
		reader = new BufferedReader(new InputStreamReader(sis));
		return reader;
	}
	
	public BufferedWriter fetchWriter(){
		OutputStream out = process.getOutputStream();
		writer = new BufferedWriter(new OutputStreamWriter(out));
		return writer;
	}
	
}
